package wechat.weblogin;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;

public class MainActivity extends AppCompatActivity {
    private EditText uuid;
    private Button confirm;
    private SimpleDateFormat simpleDateFormat;

    public void initViews() {
        uuid = (EditText) findViewById(R.id.uuid);
        confirm = (Button) findViewById(R.id.confirm);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        simpleDateFormat = new SimpleDateFormat("yyMMdd");
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = uuid.getText().toString();
                String date = simpleDateFormat.format(System.currentTimeMillis());
                String md5 = string2MD5LowerCase(date);
                Log.i("xuxingcan", date);
                Log.i("xuxingcan", md5);
                if (text.startsWith(md5)) {
                    Intent intent = new Intent("WebLoginUUID");
                    intent.putExtra("uuid", text.replace(md5, ""));
                    sendBroadcast(intent);
                    Intent in = getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
                    startActivity(in);
                } else {
                    Toast.makeText(MainActivity.this, "输入错误", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private static String string2MD5LowerCase(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().toLowerCase();
    }
}
